package repository

import (
	"apiGateWay/internal/model"
	"time"

	"gorm.io/gorm"
)

// LogRepository 日志仓库接口
type LogRepository interface {
	Create(log *model.AuditLog) error
	GetByID(id uint) (*model.AuditLog, error)
	List(params LogQueryParams) ([]*model.AuditLog, int64, error)
	DeleteOld(before time.Time) error
}

type LogQueryParams struct {
	Page      int
	PageSize  int
	Level     string
	StartTime *time.Time
	EndTime   *time.Time
	Route     string
	Method    string
}

type logRepository struct {
	db *gorm.DB
}

// NewLogRepository 创建日志仓库
func NewLogRepository(db *gorm.DB) LogRepository {
	return &logRepository{db: db}
}

func (r *logRepository) Create(log *model.AuditLog) error {
	return r.db.Create(log).Error
}

func (r *logRepository) GetByID(id uint) (*model.AuditLog, error) {
	var log model.AuditLog
	err := r.db.First(&log, id).Error
	if err != nil {
		return nil, err
	}
	return &log, nil
}

func (r *logRepository) List(params LogQueryParams) ([]*model.AuditLog, int64, error) {
	var logs []*model.AuditLog
	var total int64

	query := r.db.Model(&model.AuditLog{})

	// 构建查询条件
	if params.Level != "" {
		query = query.Where("level = ?", params.Level)
	}
	if params.StartTime != nil {
		query = query.Where("created_at >= ?", *params.StartTime)
	}
	if params.EndTime != nil {
		query = query.Where("created_at <= ?", *params.EndTime)
	}
	if params.Route != "" {
		query = query.Where("route LIKE ?", "%"+params.Route+"%")
	}
	if params.Method != "" {
		query = query.Where("method = ?", params.Method)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (params.Page - 1) * params.PageSize
	err := query.Order("created_at DESC").Offset(offset).Limit(params.PageSize).Find(&logs).Error
	return logs, total, err
}

func (r *logRepository) DeleteOld(before time.Time) error {
	return r.db.Where("created_at < ?", before).Delete(&model.AuditLog{}).Error
}


